package org.msn.gui;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.msn.client.ClientBoot;
import org.msn.client.handler.RequestHandler;
import org.msn.client.support.DefaultClientBoot;
import org.msn.config.CloseInfo;
import org.msn.gui.init.MsnInit;
import org.msn.rest.RestResult;
import org.msn.enumerate.CodeEnum;
import org.msn.gui.constant.APIConstant;
import org.msn.util.MapUtil;
import org.msn.util.RequestUtil;
import org.msn.util.YamlUtil;

import java.util.Map;

@Slf4j
public class MsnApp extends Application {
    private ClientBoot boot = new DefaultClientBoot();

    private Thread clientConnect = new Thread(() -> {
        try {
            boot.run((String) APIConstant.CONFIG.get("ip"), (int) APIConstant.CONFIG.get("port"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    @Override
    public void start(Stage primaryStage) throws Exception {
        Map<String, Object> config = YamlUtil.read("client");

        MapUtil.cloneMap(APIConstant.CONFIG, config);

        clientConnect.start();

        Parent root = FXMLLoader.load(getClass().getResource("/fxml/msnFxml.fxml"));
        primaryStage.setTitle((String) config.get("title"));
        primaryStage.setScene(new Scene(root,
                (Integer) APIConstant.CONFIG.get("width"),
                (Integer) APIConstant.CONFIG.get("height")));
        primaryStage.show();
    }

    @Override
    public void stop() throws Exception {
        super.stop();

        RestResult restResult = RestResult
                .builder()
                .code(CodeEnum.closeConnection.getCode())
                .data(CloseInfo
                        .builder()
                        .roomName(MsnInit.exportRoomName.getText())
//                        .roomName((String) APIConstant.CONFIG.get("roomName"))
                        .build())
                .build();

        // 在关闭连接之前经行一些操作 如 从房间中将人员删除 检测房间中是否还有人员存在
        RequestUtil.sendRequest(RequestHandler.ctx, restResult);

        // 关闭连接
        RequestHandler.ctx.close();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
